package cn.wolfcode.trip.app.web.controller;

import cn.wolfcode.trip.base.domain.NiceDetail;
import cn.wolfcode.trip.base.domain.TravelContent;
import cn.wolfcode.trip.base.service.INiceDetailService;
import cn.wolfcode.trip.base.service.ITravelContentService;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;
import java.util.List;

/**
 *@Discription 创建点赞记录的controller接口,实现点赞服务

 *@Params

 *@Return

 *@Authod  黄照伟

 *@CreationTime  2019/3/10 10:03

 *@change

 */
@Controller
@RequestMapping("nice")
public class NiceDetailController {
    @Autowired
    private INiceDetailService iNiceDetailService;
    //创建文章点赞的service接口
    @Autowired
    private ITravelContentService iTravelContentService;
    @RequestMapping("niceDetail")
    @ResponseBody
    public Object niceDetail(@Param("userId")Long userId, @Param("contentId")Long contentId, Model model) {

        //用户点赞模块
        
        //查询用户是否有点赞记录
        List<NiceDetail> list = iNiceDetailService.selectByUserIdAndContentId(userId, contentId);
        int result =0;

        //当id不为null,则删除原先记录,同时将文章的点赞数记录-1
        if (list!=null &&list.size()>0) {
            NiceDetail detail = list.get(0);
            //删除记录
            iNiceDetailService.delete(detail.getId());
            //根据点赞id找到文章
            TravelContent travelContent = iTravelContentService.selectByNiceId(contentId);
            if (travelContent.getNiceCount() == null) {
                travelContent.setNiceCount(0);
            } else {
                travelContent.setNiceCount(travelContent.getNiceCount() - 1);
            }
            //文章点赞数减1
            //result用于回显到前端页面
            result = travelContent.getNiceCount();
            //更新文章点赞数
            iTravelContentService.updata(travelContent);
        } else {//如果点赞记录没有值,说明没有进行点赞
            NiceDetail niceDetail = new NiceDetail();
            //添加点赞记录,同时文章数+1
            niceDetail.setUserId(userId);
            niceDetail.setContentId(contentId);
            niceDetail.setCreateTime(new Date());
            //添加记录
            iNiceDetailService.insert(niceDetail);
            //查出文章点赞记录
            TravelContent content = iTravelContentService.selectByNiceId(contentId);
            content.setNiceCount(content.getNiceCount() + 1);
            result = content.getNiceCount();
            iTravelContentService.updata(content);
        }
        return result;
    }
}
